package com.roger.uia;

import android.content.Context;
import android.net.TrafficStats;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.SystemClock;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.UiSelector;
import android.util.Log;

import com.roger.uia.helper.UiBase;
import com.roger.uia.helper.util.ExcelUtils;
import com.roger.uia.helper.util.FileUtils;
import com.roger.uia.helper.util.StrUtils;
import com.roger.uia.helper.UiWatch;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.roger.uia.helper.UiBase.mDevice;
import static com.roger.uia.helper.UiBase.waitTime;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestWifiMulti {
    private static final String TAG = TestWifiMulti.class.getSimpleName();
    private String[] wifiList;
    private Date testS,testE,pingS,pingE,connectS;
    private long checkSecurityTime,pingT,testT;
    private String isSearch,connectSuccess,isPing,baiDuN,routerN,curDate;
    @BeforeClass
    public static void beforeClass() throws Throwable {
        if(!mDevice.isScreenOn()) mDevice.wakeUp();
        mDevice.pressHome();
    }

    @Before
    public void setUp()  {
        Log.d(TAG,"-- set up --");
        FileUtils.getPermission();
        UiWatch.getWatcher().runErrorWatcher();
        UiWatch.getWatcher().runSpecialWatcher();
    }

    @After
    public void tearDown() {
        Log.d(TAG,"-- tear down --");
        UiWatch.getWatcher().removeErrorWatcher();
        UiWatch.getWatcher().removeSpecialWatcher();
    }

    @AfterClass
    public static void afterClass() throws Throwable {
        mDevice.pressHome();
        //测试结束标志
        //mDevice.executeShellCommand("am start -a android.intent.action.CALL -d tel:112");
        mDevice.executeShellCommand("am start -a android.intent.action.VIEW -d https://www.google.com/");
    }

    @Test
    public void MultiTest01_checkInternet() throws Throwable{
        removeWifiSaved();
        getWifiCfg(UiBase.filePath+"testWifi/config/wifi.cfg");
        int testTimes =Integer.parseInt(getTimesCfg(UiBase.filePath+"testWifi/config/times.cfg","times:"));
        List list = Arrays.asList(wifiList);
        Log.d(TAG,"wifi number:"+list.size()+"  test times:" + testTimes);
        for (int t=0;t<testTimes;t++){
            MtkLogOn(true);
            mDevice.pressHome();
            SystemClock.sleep(waitTime*10);
            //重新排序
            Collections.shuffle(list);
            Date date = new Date(System.currentTimeMillis());
            curDate=UiBase.dateFormat.format(date);
            //创建报告文件夹
            File fp = new File(UiBase.filePath+"testWifi/report/"+curDate);
            if (!fp.exists()) mDevice.executeShellCommand("mkdir -p " + fp);
            mDevice.executeShellCommand("cp -rf "+UiBase.filePath+"/testWifi/config/report.cfg "+UiBase.filePath+"/testWifi/report/"+curDate+"/report.xls");
            //开始测试
            for(int i=0;i<list.size();i++){
                String[] wifiInfo =  ((String) list.get(i)).split("<->");
                String isSearchable = wifiInfo[0];
                String wifiName = wifiInfo[1];
                String wifiPwd = wifiInfo[2];
                String security = wifiInfo[3];
                String routerIP = wifiInfo[4];
                testS=testE=pingS=pingE=connectS=null;
                checkSecurityTime=pingT=testT=0;
                isSearch=isPing=connectSuccess=baiDuN=routerN="/";;
                Log.d(TAG, "Wifi info:"+"wifi is searchable:"+isSearchable+";wifi name:"+wifiName+";wifi pwd:" +wifiPwd+";security:"+security+";router ip:"+routerIP);
                UiObject menuText = mDevice.findObject(new UiSelector().textMatches(wifiName));
                UiObject menuTextAdd = mDevice.findObject(new UiSelector().textMatches("(?i)Add network|添加网络"));
                String success="(?i)"+wifiName+",Connected.*|"+wifiName+",已连接.*";
                String obtainIP="(?i)"+wifiName+",Obtaining.*|"+wifiName+",正在获取.*";
                int loop =0;
                UiScrollable secMenuList = new UiScrollable(new UiSelector().resourceId(StrUtils.settingList));
                try {
                    enterWLAN();
                    testS = new Date(System.currentTimeMillis());
                    if(isSearchable.equals("true")){
                        for(int j=0;j<10;j++){
                            secMenuList.scrollIntoView(menuText);
                            if(menuText.exists()) {
                                isSearch="Y";
                                break;
                            }else {
                                SystemClock.sleep(waitTime * 5);
                            }
                        }
                        menuText.clickAndWaitForNewWindow();
                        if(!wifiPwd.equals("null")){
                            UiBase.waitObj(UiBase.objSelect[3],StrUtils.password,5);
                            UiBase.inputTxtToObj(UiBase.objSelect[3],StrUtils.password,wifiPwd);
                            if(!UiBase.objChecked(UiBase.objSelect[3],"com.android.settings:id/show_password")) UiBase.clickObj(UiBase.objSelect[3],"com.android.settings:id/show_password");
                            FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/report/"+curDate+"/pic/",wifiName+"_pwd");
                            UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.connect,10);
                        }
                        connectS = new Date(System.currentTimeMillis());
                        while (!UiBase.existObj(UiBase.objSelect[6],success) && loop < 800){
                            if(UiBase.existObj(UiBase.objSelect[6],obtainIP)){
                                pingS = new Date(System.currentTimeMillis());
                                for(int j=0;j<=1200;j++){
                                    pingE = new Date(System.currentTimeMillis());
                                    if(!UiBase.existObj(UiBase.objSelect[6],obtainIP)) {
                                        pingE = new Date(System.currentTimeMillis());
                                        pingT = pingE.getTime()-pingS.getTime();
                                        Log.d(TAG,"obtain ip normal"+pingT);
                                        isPing="N";
                                        loop = 800;
                                        break;
                                    }
                                    long pingTime = pingE.getTime()-pingS.getTime();
                                    if(pingTime>180000){
                                        isPing="Y";
                                        Log.d(TAG,"obtain ip more than 180 s"+pingTime);
                                        break;
                                    }
                                    SystemClock.sleep(100);
                                }
                                checkSecurityTime = pingS.getTime()-connectS.getTime();
                                Log.d(TAG,"checkSecurityTime:"+checkSecurityTime);
                            }
                            Log.d(TAG,"check ip before connect again");
                            SystemClock.sleep(100);
                            loop ++;
                        }
                        Log.d(TAG,"check if connecting to the internet");
                        checkConnect(success,wifiName,routerIP);
                        mDevice.pressHome();
                    }else {
                        isSearch="/";
                        for(int j=0;j<3;j++){
                            secMenuList.scrollIntoView(menuTextAdd);
                            if(menuTextAdd.exists()) {
                                menuTextAdd.clickAndWaitForNewWindow();
                                break;
                            }
                        }
                        UiBase.waitObj(UiBase.objSelect[0],"Enter the SSID",3);
                        UiBase.inputTxtToObj(UiBase.objSelect[0],"Enter the SSID",wifiName);
                        if(!wifiPwd.equals("null")){
                            UiBase.clickObj(UiBase.objSelect[3],"com.android.settings:id/security");
                            UiBase.waitClickObj(UiBase.objSelect[0],security,5);
                            UiBase.waitObj(UiBase.objSelect[3],"com.android.settings:id/password",3);
                            UiBase.inputTxtToObj(UiBase.objSelect[3],"com.android.settings:id/password",wifiPwd);
                        }
                        UiBase.waitClickObj(UiBase.objSelect[3],"com.android.settings:id/wifi_advanced_toggle",3);
                        UiBase.scrollReidClickObj("com.android.settings:id/dialog_scrollview",UiBase.objSelect[0],"No");
                        UiBase.waitClickObj(UiBase.objSelect[0],"Yes",3);
                        UiBase.waitClickObj(UiBase.objSelect[0],"SAVE",3);
                        mDevice.pressHome();
                        enterWLAN();
                        Log.d(TAG,"check if connecting to the internet");
                        checkConnect(success,wifiName,routerIP);
                        mDevice.pressHome();
                    }
                    removeWifiSaved();
                    testE = new Date(System.currentTimeMillis());
                    testT=testE.getTime()-testS.getTime();
                    Log.d(TAG,"all test time:"+testT);
                }catch (Throwable e){
                    Log.d(TAG,"something error!");
                    FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/report/"+curDate+"/pic/",wifiName+"_error");
                    removeWifiSaved();
                    testS=testE=pingS=pingE=connectS=null;
                    checkSecurityTime=pingT=testT=0;
                    isSearch=isPing=connectSuccess=baiDuN=routerN="/";
                    e.printStackTrace();
                }
                if(testE==null && pingE==null){
                    writeResult(0,i,wifiName,isSearch,connectSuccess,"/",isPing, "/", "/","/",
                            "/","/","/",baiDuN,routerN);
                }else if(pingE ==null){
                    writeResult(0,i,wifiName,isSearch,connectSuccess,"/",isPing, "/", "/","/",
                            UiBase.dateFormat.format(testS),UiBase.dateFormat.format(testE),String.valueOf(testT/1000),baiDuN,routerN);
                }else{
                    writeResult(0,i,wifiName,isSearch,connectSuccess,String.valueOf(checkSecurityTime),isPing, UiBase.dateFormat.format(pingS), UiBase.dateFormat.format(pingE),String.valueOf(pingT),
                            UiBase.dateFormat.format(testS),UiBase.dateFormat.format(testE),String.valueOf(testT/1000),baiDuN,routerN);
                }
            }
            Log.d(TAG,"cp mtklog");
            MtkLogOn(false);
            SystemClock.sleep(waitTime*10);
            mDevice.executeShellCommand("cp -r /storage/emulated/0/mtklog/ /storage/emulated/0/testWifi/report/"+curDate);
            mDevice.executeShellCommand("rm -rf /storage/emulated/0/mtklog");
        }
    }


    @Test
    public void MultiTest02_checkStreamMedia() throws Throwable{
        removeWifiSaved();
        getWifiCfg(UiBase.filePath+"testWifi/config/wifi.cfg");
        int testTimes =Integer.parseInt(getTimesCfg(UiBase.filePath+"testWifi/config/times.cfg","times:"));
        List list = Arrays.asList(wifiList);
        Log.d(TAG,"wifi number:"+list.size()+"  test times:" + testTimes);
        for (int t=0;t<testTimes;t++){
            MtkLogOn(true);
            mDevice.pressHome();
            SystemClock.sleep(waitTime*10);
            //重新排序
            Collections.shuffle(list);
            Date date = new Date(System.currentTimeMillis());
            curDate=UiBase.dateFormat.format(date);
            //创建报告文件夹
            File fp = new File(UiBase.filePath+"testWifi/report/"+curDate);
            if (!fp.exists()) mDevice.executeShellCommand("mkdir -p " + fp);
            mDevice.executeShellCommand("cp -rf "+UiBase.filePath+"/testWifi/config/report.cfg "+UiBase.filePath+"/testWifi/report/"+curDate+"/report.xls");
            //开始测试
            for(int i=0;i<list.size();i++){
                String[] wifiInfo =  ((String) list.get(i)).split("<->");
                String isSearchable = wifiInfo[0];
                String wifiName = wifiInfo[1];
                String wifiPwd = wifiInfo[2];
                String security = wifiInfo[3];
                String routerIP = wifiInfo[4];
                testS=testE=pingS=pingE=connectS=null;
                checkSecurityTime=pingT=testT=0;
                isSearch=isPing=connectSuccess=baiDuN=routerN="/";;
                Log.d(TAG, "Wifi info:"+"wifi is searchable:"+isSearchable+";wifi name:"+wifiName+";wifi pwd:" +wifiPwd+";security:"+security+";router ip:"+routerIP);
                UiObject menuText = mDevice.findObject(new UiSelector().textMatches(wifiName));
                UiObject menuTextAdd = mDevice.findObject(new UiSelector().textMatches("(?i)Add network|添加网络"));
                String success="(?i)"+wifiName+",Connected.*|"+wifiName+",已连接.*";
                String obtainIP="(?i)"+wifiName+",Obtaining.*|"+wifiName+",正在获取.*";
                int loop =0;
                UiScrollable secMenuList = new UiScrollable(new UiSelector().resourceId(StrUtils.settingList));
                try {
                    enterWLAN();
                    testS = new Date(System.currentTimeMillis());
                    if(isSearchable.equals("true")){
                        for(int j=0;j<10;j++){
                            secMenuList.scrollIntoView(menuText);
                            if(menuText.exists()) {
                                isSearch="Y";
                                break;
                            }else {
                                SystemClock.sleep(waitTime * 5);
                            }
                        }
                        menuText.clickAndWaitForNewWindow();
                        if(!wifiPwd.equals("null")){
                            UiBase.waitObj(UiBase.objSelect[3],StrUtils.password,5);
                            UiBase.inputTxtToObj(UiBase.objSelect[3],StrUtils.password,wifiPwd);
                            if(!UiBase.objChecked(UiBase.objSelect[3],"com.android.settings:id/show_password")) UiBase.clickObj(UiBase.objSelect[3],"com.android.settings:id/show_password");
                            FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/report/"+curDate+"/pic/",wifiName+"_pwd");
                            UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.connect,10);
                        }
                        connectS = new Date(System.currentTimeMillis());
                        while (!UiBase.existObj(UiBase.objSelect[6],success) && loop < 800){
                            if(UiBase.existObj(UiBase.objSelect[6],obtainIP)){
                                pingS = new Date(System.currentTimeMillis());
                                for(int j=0;j<=1200;j++){
                                    pingE = new Date(System.currentTimeMillis());
                                    if(!UiBase.existObj(UiBase.objSelect[6],obtainIP)) {
                                        pingE = new Date(System.currentTimeMillis());
                                        pingT = pingE.getTime()-pingS.getTime();
                                        Log.d(TAG,"obtain ip normal"+pingT);
                                        isPing="N";
                                        loop = 800;
                                        break;
                                    }
                                    long pingTime = pingE.getTime()-pingS.getTime();
                                    if(pingTime>180000){
                                        isPing="Y";
                                        Log.d(TAG,"obtain ip more than 180 s"+pingTime);
                                        break;
                                    }
                                    SystemClock.sleep(100);
                                }
                                checkSecurityTime = pingS.getTime()-connectS.getTime();
                                Log.d(TAG,"checkSecurityTime:"+checkSecurityTime);
                            }
                            Log.d(TAG,"check ip before connect again");
                            SystemClock.sleep(100);
                            loop ++;
                        }
                        Log.d(TAG,"check if connecting to the internet");
                        checkVideo(success,wifiName,routerIP);
                        mDevice.pressHome();
                    }else {
                        isSearch="/";
                        for(int j=0;j<3;j++){
                            secMenuList.scrollIntoView(menuTextAdd);
                            if(menuTextAdd.exists()) {
                                menuTextAdd.clickAndWaitForNewWindow();
                                break;
                            }
                        }
                        UiBase.waitObj(UiBase.objSelect[0],"Enter the SSID",3);
                        UiBase.inputTxtToObj(UiBase.objSelect[0],"Enter the SSID",wifiName);
                        if(!wifiPwd.equals("null")){
                            UiBase.clickObj(UiBase.objSelect[3],"com.android.settings:id/security");
                            UiBase.waitClickObj(UiBase.objSelect[0],security,5);
                            UiBase.waitObj(UiBase.objSelect[3],"com.android.settings:id/password",3);
                            UiBase.inputTxtToObj(UiBase.objSelect[3],"com.android.settings:id/password",wifiPwd);
                        }
                        UiBase.waitClickObj(UiBase.objSelect[3],"com.android.settings:id/wifi_advanced_toggle",3);
                        UiBase.scrollReidClickObj("com.android.settings:id/dialog_scrollview",UiBase.objSelect[0],"No");
                        UiBase.waitClickObj(UiBase.objSelect[0],"Yes",3);
                        UiBase.waitClickObj(UiBase.objSelect[0],"SAVE",3);
                        mDevice.pressHome();
                        enterWLAN();
                        Log.d(TAG,"check if connecting to the internet");
                        checkVideo(success,wifiName,routerIP);
                        mDevice.pressHome();
                    }
                    removeWifiSaved();
                    testE = new Date(System.currentTimeMillis());
                    testT=testE.getTime()-testS.getTime();
                    Log.d(TAG,"all test time:"+testT);
                }catch (Throwable e){
                    Log.d(TAG,"something error!");
                    FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/report/"+curDate+"/pic/",wifiName+"_error");
                    removeWifiSaved();
                    testS=testE=pingS=pingE=connectS=null;
                    checkSecurityTime=pingT=testT=0;
                    isSearch=isPing=connectSuccess=baiDuN=routerN="/";
                    e.printStackTrace();
                }
                if(testE==null && pingE==null){
                    writeResult(1,i,wifiName,isSearch,connectSuccess,"/",isPing, "/", "/","/",
                            "/","/","/",baiDuN,routerN);
                }else if(pingE ==null){
                    writeResult(1,i,wifiName,isSearch,connectSuccess,"/",isPing, "/", "/","/",
                            UiBase.dateFormat.format(testS),UiBase.dateFormat.format(testE),String.valueOf(testT/1000),baiDuN,routerN);
                }else{
                    writeResult(1,i,wifiName,isSearch,connectSuccess,String.valueOf(checkSecurityTime),isPing, UiBase.dateFormat.format(pingS), UiBase.dateFormat.format(pingE),String.valueOf(pingT),
                            UiBase.dateFormat.format(testS),UiBase.dateFormat.format(testE),String.valueOf(testT/1000),baiDuN,routerN);
                }
            }
            Log.d(TAG,"cp mtklog");
            MtkLogOn(false);
            SystemClock.sleep(waitTime*10);
            mDevice.executeShellCommand("cp -r /storage/emulated/0/mtklog/ /storage/emulated/0/testWifi/report/"+curDate);
            mDevice.executeShellCommand("rm -rf /storage/emulated/0/mtklog");
        }
    }

    @Test
    public void MultiTest03_checkStreamMediaOnly() throws Throwable{
        //吞吐率
        Date dateS = new Date(System.currentTimeMillis());
        curDate=UiBase.dateFormat.format(dateS);
        int times= 0;
        int allTimes=60 * Integer.parseInt(getTimesCfg(UiBase.filePath+"testWifi/config/times.cfg","video:"));
        Log.d(TAG,"start test wifi Throughput rate for " +allTimes/60 +" min");
        long downloadShow=0;
        long uploadShow=0;
        while(times<allTimes){
            times++;
            Date date = new Date(System.currentTimeMillis());
            String time = UiBase.dateFormat.format(date);
            long downloadData1 = TrafficStats.getTotalRxBytes();
            long uploadData1 = TrafficStats.getTotalTxBytes();
            SystemClock.sleep(1000);
            long downloadData2 = TrafficStats.getTotalRxBytes();
            long uploadData2 = TrafficStats.getTotalTxBytes();
            downloadShow = (downloadData2 - downloadData1) / 1024;
            uploadShow = (uploadData2 - uploadData1) / 1024;
            if(downloadShow==0){
                FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/report/"+curDate+"/videoCap/","Lag");
            }
            //Log.d(TAG, time +":"+ String.valueOf(downloadShow)+"kb/s  "+String.valueOf(uploadShow)+"kb/s"+" ping:"+pingTxt);
            writeWifiData(times,"result",time,String.valueOf(uploadShow),String.valueOf(downloadShow),"/");
        }

    }

    private static void MtkLogOn(boolean b){
        try{
            //create contacts
            UiBase.openApp("com.android.contacts");
            UiBase.waitClickObj(UiBase.objSelect[3],"com.android.contacts:id/floating_action_button",5);
            UiBase.inputTxtToObj(UiBase.objSelect[0],"First name","Test");
            UiBase.clickObj(UiBase.objSelect[0],"SAVE");
            mDevice.pressBack();
            if(!UiBase.existObj(UiBase.objSelect[3],"com.android.contacts:id/menu_search"))UiBase.openApp("com.android.contacts");
            UiBase.waitClickObj(UiBase.objSelect[3],"com.android.contacts:id/menu_search",5);
            UiBase.inputTxtToObj(UiBase.objSelect[0],"Search contacts","####3333#");
            UiBase.waitObj(UiBase.objSelect[3], "com.mediatek.mtklogger:id/startStopToggleButton",3);
            if(b){
                if(UiBase.existObj(UiBase.objSelect[3], "com.mediatek.mtklogger:id/startStopToggleButton")
                        && !UiBase.objChecked(UiBase.objSelect[3], "com.mediatek.mtklogger:id/startStopToggleButton")) {
                    UiBase.clickObj(UiBase.objSelect[3], "com.mediatek.mtklogger:id/startStopToggleButton");
                    UiBase.waitClickObj(UiBase.objSelect[3], "android:id/button1",3);
                }
            }else{
                if(UiBase.existObj(UiBase.objSelect[3], "com.mediatek.mtklogger:id/startStopToggleButton")
                        && UiBase.objChecked(UiBase.objSelect[3], "com.mediatek.mtklogger:id/startStopToggleButton")) {
                    UiBase.clickObj(UiBase.objSelect[3], "com.mediatek.mtklogger:id/startStopToggleButton");
                    UiBase.waitClickObj(UiBase.objSelect[3], "android:id/button1",3);
                }
            }
            SystemClock.sleep(waitTime * 5);
        }catch (Throwable e){
            e.printStackTrace();
        }
    }

    //进入wifi搜索界面
    private void enterWLAN() throws Throwable {
        if (UiBase.existObj(UiBase.objSelect[2],StrUtils.wifi) && UiBase.existObj(UiBase.objSelect[3],StrUtils.frictionIcon)) {
            SystemClock.sleep(waitTime);
        } else {
            mDevice.pressHome();
            UiBase.openApp(StrUtils.settingPac);
            UiBase.waitObj(UiBase.objSelect[3],StrUtils.settingDashBoard,10);
            UiBase.scrollReidClickObj(StrUtils.settingDashBoard,UiBase.objSelect[2],StrUtils.settingNetwork);
            UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.wifi,5);
            UiBase.waitObj(UiBase.objSelect[3],StrUtils.switch_widget,5);
            if (UiBase.getTxtFromObj(UiBase.objSelect[3],StrUtils.switch_widget).matches(StrUtils.off)) {
                UiBase.clickObj(UiBase.objSelect[3],StrUtils.switch_widget);
                SystemClock.sleep(waitTime * 10);
            }
            SystemClock.sleep(waitTime);
        }
    }

    //网络连接检测
    private void checkConnect(String s,String name,String ip) throws Throwable {
        UiBase.waitObj(UiBase.objSelect[6],s,30);
        FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/report/"+curDate+"/pic/",name+"_WifiList");
        if (UiBase.existObj(UiBase.objSelect[6],s)){
            connectSuccess="Y";
            mDevice.pressHome();
            //open www.baidu.com
            mDevice.executeShellCommand("am start -a android.intent.action.VIEW -d https://www.baidu.com");
            UiBase.waitObj(UiBase.objSelect[0],"百度一下,你就知道",25);
            SystemClock.sleep(waitTime);
            //ping
            mDevice.executeShellCommand("sh /data/local/tmp/ping.sh "+name+"_baidu"+" www.baidu.com");
            String baiDuP=mDevice.executeShellCommand("cat storage/emulated/0/testWifi/ping/"+name+"_baidu"+".txt");
            SystemClock.sleep(waitTime);
            mDevice.executeShellCommand("sh /data/local/tmp/ping.sh "+name+"_routerIP"+" "+ip);
            String routerP=mDevice.executeShellCommand("cat storage/emulated/0/testWifi/ping/"+name+"_routerIP"+".txt");
            SystemClock.sleep(waitTime);
            //mDevice.executeShellCommand("mv -f /storage/emulated/0/testWifi/ping/ /storage/emulated/0/testWifi/report/"+curDate);
            mDevice.executeShellCommand("cp -r /storage/emulated/0/testWifi/ping/ /storage/emulated/0/testWifi/report/"+curDate);
            mDevice.executeShellCommand("rm -rf /storage/emulated/0/testWifi/ping");
            //result
            SystemClock.sleep(waitTime);
            FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/report/"+curDate+"/pic/",name+"_checkInternet");
            if(!UiBase.existObj(UiBase.objSelect[0],"百度一下,你就知道")){
                baiDuN="N";
            }else if(baiDuP.contains("received, 0% packet loss")){
                baiDuN="Y";
            }else{
                baiDuN="open BaiDu success but some packet loss";
            }
            if(routerP.contains("received, 0% packet loss")){
                routerN="Y";
            }else if(routerP.contains("packet loss")){
                routerN="packet loss";
            }else{
                routerN="N";
            }
        }else{
            connectSuccess="N";
            baiDuN=routerN="/";
        }
        Log.d(TAG,connectSuccess+" "+baiDuN+" "+routerN);
    }

    //Video检测
    private void checkVideo(String s, final String name, String ip) throws Throwable {
        UiBase.waitObj(UiBase.objSelect[6],s,30);
        FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/report/"+curDate+"/pic/",name+"_WifiList");
        if (UiBase.existObj(UiBase.objSelect[6],s)){
            connectSuccess="Y";
            mDevice.pressHome();
            //open Video
            Log.d(TAG,"open video");
            mDevice.executeShellCommand("am force-stop air.tv.douyu.android");
            playVideo();
            SystemClock.sleep(waitTime * 5);
//            Thread VideoMonitor=new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        mDevice.executeShellCommand("sh /data/local/tmp/videorecord.sh "+curDate+" "+name+" &");
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }) ;
//            VideoMonitor.start();
//            Log.d(TAG,"start monitor Video");
            //吞吐率
            int times= 0;
            int allTimes=60 * Integer.parseInt(getTimesCfg(UiBase.filePath+"testWifi/config/times.cfg","video:"));
            Log.d(TAG,"start test wifi Throughput rate for " +allTimes/60 +" min");
            long downloadShow=0;
            long uploadShow=0;
            while(times<allTimes){
                times++;
                String pingTxt="/";
                //WifiManager wifiManager = (WifiManager) InstrumentationRegistry.getTargetContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                //WifiInfo connectionInfo = wifiManager.getConnectionInfo();
                //int wifiLinked = connectionInfo.getLinkSpeed();
                Date date = new Date(System.currentTimeMillis());
                String time = UiBase.dateFormat.format(date);
                long downloadData1 = TrafficStats.getTotalRxBytes();
                long uploadData1 = TrafficStats.getTotalTxBytes();
                mDevice.executeShellCommand("sh /data/local/tmp/ping4hour.sh "+name+" "+ip);
                SystemClock.sleep(650);
                long downloadData2 = TrafficStats.getTotalRxBytes();
                long uploadData2 = TrafficStats.getTotalTxBytes();
                downloadShow = (downloadData2 - downloadData1) / 1024;
                uploadShow = (uploadData2 - uploadData1) / 1024;
                if(downloadShow==0){
                    FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/report/"+curDate+"/videoCap/","Lag");
                }
                pingTxt=mDevice.executeShellCommand("cat "+ UiBase.filePath+"testWifi/ping/"+name+".txt");
                //Log.d(TAG, time +":"+ String.valueOf(downloadShow)+"kb/s  "+String.valueOf(uploadShow)+"kb/s"+" ping:"+pingTxt);
                writeWifiData(times,name,time,String.valueOf(uploadShow),String.valueOf(downloadShow),pingTxt);
            }
            //kill pid
            String videoPid =mDevice.executeShellCommand("cat /data/local/tmp/video_pid.txt");
            mDevice.executeShellCommand("kill -9 "+videoPid);
            Log.d(TAG,"kill videoPid success: "+videoPid);
//            VideoMonitor.interrupted();
            FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/report/"+curDate+"/pic/",name+"_checkInternet");
            SystemClock.sleep(waitTime * 5);
            mDevice.executeShellCommand("am force-stop air.tv.douyu.android");
            if(FileUtils.existFile(UiBase.filePath+"testWifi/report/"+curDate+"/wifiData/"+name+".xls")) baiDuN="Y";
            if(FileUtils.existFile(UiBase.filePath+"testWifi/ping/"+name+".txt")) routerN="Y";
            mDevice.executeShellCommand("rm -rf "+UiBase.filePath+"testWifi/ping/"+name+".txt");
        }else{
            connectSuccess="N";
            baiDuN=routerN="/";
            mDevice.pressHome();
        }
        Log.d(TAG,connectSuccess+" "+baiDuN+" "+routerN);
    }

    //解析wifi配置文件
    private void getWifiCfg(String path){
        try {
            File file = new File(path);
            FileInputStream is = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(is,"gbk"));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                if(!line.startsWith("#")){
                    stringBuilder.append(line);
                    stringBuilder.append("\n");
                }
            }
            wifiList=stringBuilder.toString().split("\n");
            br.close();
            is.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //解析times配置文件
    private String getTimesCfg(String path,String startTag){
        String s ="";
        try {
            File file = new File(path);
            FileInputStream is = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(is,"gbk"));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                if(line.startsWith(startTag)){
                    stringBuilder.append(line);
                }
            }
            s = stringBuilder.toString().replaceAll(startTag,"");
            br.close();
            is.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return s;
    }

    //移除已保存的wifi
    private void removeWifiSaved(){
        try{
            WifiManager wifiManager = (WifiManager) InstrumentationRegistry.getTargetContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            List<WifiConfiguration> wifiConfigs = wifiManager.getConfiguredNetworks();
            if(!String.valueOf(wifiConfigs).equals("[]")){
                enterWLAN();
                UiScrollable secMenuList = new UiScrollable(new UiSelector().resourceId(StrUtils.settingList));
                for(int j=0;j<10;j++){
                    secMenuList.scrollIntoView(UiBase.getObj(UiBase.objSelect[2],StrUtils.savedWifi));
                    if(UiBase.existObj(UiBase.objSelect[2],StrUtils.savedWifi)) {
                        UiBase.clickObj(UiBase.objSelect[2],StrUtils.savedWifi);
                        for (WifiConfiguration wifiConfig : wifiConfigs) {
                            String name = String.valueOf(wifiConfig.SSID.replaceAll("\"",""));
                            Log.d(TAG,"remove wifi : "+ name);
                            if (UiBase.existObj(UiBase.objSelect[0],name)){
                                UiBase.clickObj(UiBase.objSelect[0],name);
                                UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.forget,3);
                            }
                        }
                        break;
                    }else {
                        Log.d(TAG,"no find saved wifi");
                    }
                }
            }else{
                Log.d(TAG,"no saved wifi");
            }
        }catch (Throwable e){
            Log.d(TAG,"remove saved wifi fail");
            e.printStackTrace();
        }finally {
            mDevice.pressHome();
        }
    }

    private void playVideo(){
        try {
            UiBase.openApp("air.tv.douyu.android");
            //检测更新
            UiBase.waitObj(UiBase.objSelect[3],"air.tv.douyu.android:id/b2k",10);
            if(UiBase.existObj(UiBase.objSelect[3],"air.tv.douyu.android:id/b2k")) UiBase.clickObj(UiBase.objSelect[3],"air.tv.douyu.android:id/b2k");
            //查询历史记录并播放
            UiBase.waitClickObj(UiBase.objSelect[3],"air.tv.douyu.android:id/cem",10);
            UiBase.waitClickObj(UiBase.objSelect[1],"s1134",20);
        }catch (Throwable e){
            Log.d(TAG,"play video fail");
            e.printStackTrace();
        }
    }

    //写入结果
    private void writeResult(int sheet,int num,String name,String search,String suc,String sec,String ping ,String ping1,String ping2,String ping3,String startT,String endT,String costT,String baiDuB,String routerB ){
        String [] result ={String.valueOf(num+1),name,search,suc,sec,ping,ping1,ping2,ping3,startT,endT,costT,baiDuB,routerB};
        for(int i=0;i<result.length;i++){
            ExcelUtils.addExcelData(UiBase.filePath+"testWifi/report/"+curDate+"/report.xls",sheet,(num+2),(short) i,result[i]);
        }
    }

    private void writeWifiData(int num, String name, String timeNow ,String up, String down, String ping){
        if(!FileUtils.existFile(UiBase.filePath+"testWifi/report/"+curDate+"/wifiData/"+name+".xls")){
            String[] title = {"次数","时间","上行速率(kb/s)","下行速率(kb/s)","Ping(ms)"};
            ExcelUtils.createExcel(UiBase.filePath+"testWifi/report/"+curDate+"/wifiData/"+name+".xls",title);
        }
        String [] result ={String.valueOf(num),timeNow,up,down,ping};
        for(int i=0;i<result.length;i++){
            ExcelUtils.addExcelData(UiBase.filePath+"testWifi/report/"+curDate+"/wifiData/"+name+".xls",0,(num),(short) i,result[i]);
        }
    }

}